<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { Gender, Profile } from '@/types/member'
import { getMemberProfile, updateMemberProfile } from '@/api/member'
import { toRef, ref } from 'vue'
import useAppStore from '@/store'
import { useMemeberStore } from '@/store/member'
const memberStore = useMemeberStore()

const appStore = useAppStore()
const safeArea = toRef(appStore, 'safeArea')

const goBack = () => {
  uni.navigateBack({})
}

const chooseImage = () => {
  uni.chooseImage({
    count: 1, // 最多可以选择的图片张数，默认9
    success: (res: UniApp.ChooseImageSuccessCallbackResult) => {
      const filePath = res.tempFilePaths[0]
      uni.uploadFile({
        url: '/member/profile/avatar',
        name: 'file', // 后台对应的参数名
        filePath,
        success: res2 => {
          if (res2.statusCode === 200) {
            const resObj = JSON.parse(res2.data)
            // 更新模型中的头像
            memberProfile.value.avatar = resObj.result.avatar
            // 更新仓库中的头像
            memberStore.profile.avatar = resObj.result.avatar
          }
        }
      })
    }
  })
}

const memberProfile = ref({} as Profile)
onLoad(async () => {
  memberProfile.value = await getMemberProfile()
})

// 性别修改
const genderChange = (e: WechatMiniprogram.RadioGroupChange) => {
  memberProfile.value.gender = e.detail.value as Gender
}

// 出生日期修改
const birthdayChange = (e: WechatMiniprogram.PickerChange) => {
  memberProfile.value.birthday = e.detail.value as string
}

// 省市区修改
// 省市区的名称修改 - Picker mode="region"
let fullLocationCode: string[] = []
const fullLocationChange = (e: WechatMiniprogram.PickerChange) => {
  memberProfile.value.fullLocation = (e.detail.value as string[]).join('')
  fullLocationCode = e.detail.code
}

// 修改个人信息
const submit = async () => {
  const { nickname, gender, birthday, profession } = memberProfile.value
  const [provinceCode, cityCode, countyCode] = fullLocationCode
  await updateMemberProfile({
    nickname,
    gender,
    birthday,
    profession,
    provinceCode,
    cityCode,
    countyCode
  })

  // 成功提示
  uni.showToast({ title: '修改成功~' })
  // 🐛 同步修改本地 Store 的昵称
  memberStore.profile.nickname = nickname
  // 后退返回上一页（正常的流程：个人中心点击修改资料跳转到当前页，修改完成后退回去）
  // 🚨注意事项：开发时编译模式直接打开的话，没有上一页的历史记录会报错(此报错不用修复)
  uni.navigateBack({})
}
</script>

<template>
  <view class="viewport">
    <view class="navbar" :style="{ paddingTop: safeArea?.top + 'px' }">
      <view class="back icon-left" @click="goBack"></view>
      <view class="title">个人信息</view>
    </view>
    <scroll-view scroll-y>
      <!-- 头像 -->
      <view class="avatar" @click="chooseImage">
        <image :src="memberProfile.avatar" mode="aspectFill" />
        <text>点击修改头像</text>
      </view>
      <!-- 用户信息 -->
      <view class="form">
        <view class="form-item">
          <text class="label">账号</text>
          <!-- <input readonly :value="memberProfile.account" />t -->
          <text>{{ memberProfile.account }}</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input v-model="memberProfile.nickname" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="genderChange">
            <label class="radio">
              <radio
                value="男"
                color="#27ba9b"
                :checked="memberProfile.gender === '男'"
              />
              男
            </label>
            <label class="radio">
              <radio
                value="女"
                color="#27ba9b"
                :checked="memberProfile.gender === '女'"
              />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">出生日期</text>
          <picker
            mode="date"
            start="1900-01-01"
            end="2023-01-01"
            @change="birthdayChange"
          >
            <view>{{ memberProfile.birthday || '请选择出生日期' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">城市</text>
          <picker mode="region" @change="fullLocationChange">
            <view>{{ memberProfile.fullLocation || '请选择城市' }}</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">职业</text>
          <input v-model="memberProfile.profession" placeholder="请填写职业" />
        </view>
      </view>
      <!-- 提交按钮 -->
      <view class="button" @click="submit">保 存</view>
    </scroll-view>
  </view>
</template>

<style>
page {
  height: 100%;
  overflow: hidden;
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(http://static.botue.com/erabbit/static/images/order_bg.png);
  background-size: auto 392rpx;
  background-repeat: no-repeat;
}

.navbar .title {
  height: 40px;
  line-height: 32px;
  text-align: center;
  font-size: 17px;
  font-weight: 500;
  color: #fff;
}

.navbar .back {
  position: absolute;
  left: 20rpx;
  top: 22px;
  font-size: 23px;
  z-index: 9;
  color: #fff;
}

.avatar {
  text-align: center;
  padding: 20rpx 0 40rpx;
}

.avatar image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
}

.avatar text {
  display: block;
  padding-top: 20rpx;
  line-height: 1;
  font-size: 26rpx;
  color: #fff;
}

.form {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;
}

.form .form-item {
  display: flex;
  height: 96rpx;
  line-height: 46rpx;
  padding: 25rpx 10rpx;
  background-color: #fff;
  font-size: 28rpx;
  border-bottom: 1rpx solid #ddd;
}

.form .form-item:last-child {
  border: none;
}

.form .form-item .label {
  width: 180rpx;
  color: #333;
}

.form .form-item input {
  flex: 1;
  display: block;
  height: 46rpx;
}

.form .form-item .radio {
  display: inline-block;
  height: 46rpx;
  margin-right: 20rpx;
  vertical-align: middle;
}

.form .form-item radio {
  transform: scale(0.7) translateY(-2px);
}

.form .form-item picker {
  flex: 1;
}

.button {
  height: 80rpx;
  text-align: center;
  line-height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>
